<template>
  <div>
    <div class="table-page-search-wrapper">
      <a-form-model
        layout="inline"
        :model="queryParam"
      >
        <a-row :gutter="15">
          <a-col :md="6" :sm="24">
            <a-form-model-item label="合同编号">
              <a-input v-model="queryParam['filter[contract_no]']" placeholder="请输入合同编号" :allowClear="true" />
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-model-item label="业务编号">
              <a-input v-model="queryParam['filter[business_no]']" placeholder="请输入业务编号" :allowClear="true" />
            </a-form-model-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="商标名称">
                <a-input v-model="queryParam['filter[sb_name]']" placeholder="请输入商标名称" :allowClear="true" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="业务名称">
                <a-select v-model="queryParam['filter[business_id]']" placeholder="请选择业务名称" :allowClear="true">
                  <a-select-option v-for="(item, index) in businessOpts" :key="index" :value="item.business_id">{{item.name}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="开启时间">
                <a-range-picker @change="onChangeTime" v-model="queryParam['open_time_start']"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="商标注册号">
                <a-input v-model="queryParam['filter[sb_reg_no]']" placeholder="请输入商标注册号" :allowClear="true" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="未填写注册号">
                <a-select v-model="queryParam['filter[is_reg_no]']" placeholder="请选择是否填写了注册号/申请号" :allowClear="true">
                  <a-select-option :value="1">填写注册号</a-select-option>
                  <a-select-option :value="100">未填写注册号</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="是否上传">
                <a-select v-model="queryParam['filter[is_state]']" placeholder="请选择是否上传了回执类文件" :allowClear="true">
                  <a-select-option :value="1">已上传</a-select-option>
                  <a-select-option :value="100">未上传</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="所属顾问">
                <a-select
                  show-search
                  v-model="queryParam['filter[adviser_uid]']"
                  placeholder="请选择所属顾问"
                  :filter-option="filterOption"
                >
                  <a-select-option v-for="(item,index) in adviserOpts" :key="index" :value="index">{{item}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class='table-page-search-submitButtons' :style="advanced && { float: 'right', overflow: 'hidden' } || {}">
                <a-button type="primary" @click="$refs.table.refresh(true)">搜索</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <div class="table-operator">
      <s-table
        bordered
        ref="table"
        :row-key="(record) => record.cb_id"
        :columns="tradeColumns"
        :data="receiptData"
      >
        <div slot="title">
          <a-button size="small" type="primary" icon="import" @click="onImport">批量导入受通</a-button>
          <a-button size="small" style="margin-left:5px" type="primary" icon="setting" @click="onSetting">批量设置注册号</a-button>
        </div>
        <div
          slot="filterDropdown"
          slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
          style="padding: 8px"
        >
          <a-input
            v-ant-ref="c => (searchInput = c)"
            :placeholder="`搜索${column.title}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block;"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
            @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          />
          <a-button
            type="primary"
            icon="search"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            搜索
          </a-button>
          <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
            重置
          </a-button>
        </div>
        <template slot="contract_no" slot-scope="text,record">
          <a-popover trigger="hover">
            <template slot="content">
              <p>合同编号：{{text}}<a-divider type="vertical" /><a-icon class="copy" :data-clipboard-text="text" type="copy" @click="copy" /></p>
              <p>业务编号：{{record.business_no}}<a-divider type="vertical" /><a-icon class="copy" :data-clipboard-text="record.business_no" type="copy" @click="copy" /></p>
            </template>
            {{text}}<br>
            <a @click="toDetail(record.cb_id)">{{record.business_no}}</a>
          </a-popover>
        </template>
        <template slot="adviser" slot-scope="text, record">
          <a-tag>{{text}}</a-tag><br>
          <a-tag>{{record.group_type}}组</a-tag><br>
          <a-tag>{{record.leader}}</a-tag>
        </template>
        <template slot="sb_reg_no" slot-scope="text, record">
          {{text}}<br>
          {{record.official_order_no}}
        </template>
        <template slot="filename" slot-scope="text, record">
          <a @click="download(record.file_url, text)">{{text}}</a>
        </template>
        <template slot="state_name" slot-scope="text,record">
          <div v-if="text === ''">
            <a-tag color="red">{{record.status2}}</a-tag>
          </div>
          <div v-else>
            <a-tag color="red">[官方]{{text}}</a-tag>
          </div>
        </template>
        <template slot="cost_fee" slot-scope="text">
          <a-tag color="red">{{text}}元</a-tag><br>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button size="small" type="primary" @click="trademarkModal(record.cb_id)">编辑</a-button>
          <a-button size="small" type="default" @click="toDetail(record.cb_id)">查看</a-button>
          <a-button size="small" type="danger" @click="resetStatus(record.cb_id)">状态</a-button>
        </template>
      </s-table>
    </div>
    <a-modal
      centered
      :destroy-on-close="true"
      title="商标业务"
      :confirm-loading="loading"
      v-model="trademarkVisible"
      @ok="submitTrademark"
    >
      <a-form-model :label-col="tklabelCol" :wrapper-col="tkwrapperCol">
        <a-form-model-item label="商标名称" >
          <a-input type="text" placeholder="请输入商标名称" v-model="changeForm.sb_name"/>
        </a-form-model-item>
        <a-form-model-item label="商标类别" >
          <a-input type="text" placeholder="请输入商标类别" v-model="changeForm.sb_category"/>
        </a-form-model-item>
        <a-form-model-item label="商标注册号" >
          <a-input type="text" placeholder="请输入商标注册号" v-model="changeForm.sb_reg_no"/>
        </a-form-model-item>
        <a-form-model-item label="官方申请号" >
          <a-input type="text" placeholder="请输入官方申请号" v-model="changeForm.official_order_no"/>
        </a-form-model-item>
        <a-form-model-item label="回执类型">
          <a-select v-model="changeForm.state_id">
            <a-select-option v-for="(item,index) in receiptList" :key="index" :value="index">{{item}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <!--          <a-form-model-item label="图形商标缩略图">-->
        <!--            <a-upload-->
        <!--              name="file"-->
        <!--              accept=".jpg,.png.gif"-->
        <!--              list-type="picture-card"-->
        <!--              class="avatar-uploader"-->
        <!--              :show-upload-list="false"-->
        <!--              :action="https://www.mocky.io/v2/5cc8019d300000980a055e76"-->
        <!--            >-->
        <!--              <div>-->
        <!--                <a-icon :type="loading ? 'loading' : 'plus'" />-->
        <!--                <div class="ant-upload-text">-->
        <!--                  上传缩略图-->
        <!--                </div>-->
        <!--              </div>-->
        <!--            </a-upload>-->
        <!--          </a-form-model-item>-->
        <a-form-model-item label="文件">
          <a-upload
            name="file"
            :action="uploadUrl"
            :headers="headers"
            @change="onChange"
          >
            <a-button size="small" type="primary" icon="upload">上传回执文件</a-button>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
      <a-form-model-item label="回执历史">
        <a-timeline v-if="receiptState.length > 0">
          <a-timeline-item v-for="(item,index) in receiptState" :key="index">
            {{item.created_at}}  {{item.uid}}  添加回执【{{item.state_name}}】  <a :href="item.file">{{item.filename}}</a>  <a-button size="small" type="link" icon="delete" @click="delState(item.cbs_id)">删除</a-button>
          </a-timeline-item>
        </a-timeline>
      </a-form-model-item>
    </a-modal>
    <a-modal
      centered
      title="重置业务流程状态"
      :confirm-loading="loading"
      v-model="stateVisible"
      @ok="submitResetStatus"
    >
      <a-alert message="！！！主要针对【商标双保】业务，请谨慎操作。" type="warning"  show-icon/>
      <a-radio-group @change="onChangeRadio" style="margin-top: 20px">
        <a-radio v-for="(item, index) in changeStatusOpts" :key="index" :value="index">{{item}}</a-radio>
      </a-radio-group>
    </a-modal>
    <a-modal
      title="上传日志"
      v-model="historyVisible"
      :width="1600"
      :footer="null"
    >
      <s-table
        bordered
        ref="table2"
        size="middle"
        :row-key="(record) => record.log_id"
        :columns="historyColumns"
        :data="historyData"
      >
        <template slot="action">
          <a-button type="primary" size="small">详情</a-button>
        </template>
      </s-table>
    </a-modal>
    <batch-action v-if="settingsVisible" @cancel="onSetCancel"></batch-action>
    <batch-action2 v-if="settingsVisible2" @cancel="onSetCancel2"></batch-action2>
    <a-modal
      title="批量导入回执"
      v-model="importVisible"
      :destroy-on-close="true"
      @ok="onSubmit"
    >
      <a-form-model
        ref="importForm"
        :model="importForm"
        :rules="importRules"
      >
        <a-form-model-item label="业务分类" prop="business_id">
          <a-select
            v-model="importForm.busienss_id"
            placeholder="请选择业务分类"
            @change="onSelect"
          >
            <a-select-option v-for="item in businessOpts" :key="item.business_id" :value="item.business_id">{{item.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="官方状态" prop="state_id">
          <a-select
            v-model="importForm.state_id"
            placeholder="请选择业务分类"
            @change="onSelect2"
          >
            <a-select-option v-for="(item,index) in stateOpts" :key="index" :value="index">{{item}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="上传回执压缩包" prop="filename">
          <a-upload
            name="file"
            accept=".zip"
            :headers="headers"
            :action="uploadUrl"
            @change="changeUpload"
          >
            <a-button type="danger" icon="upload" size="small">上传受通压缩包</a-button>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import { STable, Ellipsis } from '@/components'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import apis from '@/api'
import trademarkColumns from '@/columns/tm.process'
import {
  getCollectList, getImport, getImportByState, getReceiptDelete, getReceiptList, getReceiptState,
  getTrademarkEdit,
  getTrademarkStatusEdit, postImport,
  postReceiptState,
  postTrademarkEdit, postTrademarkStatusEdit
} from '@/api/tm.process'
import BatchAction from '@/views/tm-process/components/BatchAction'
import BatchAction2 from '@/views/tm-process/components/BatchAction2'

export default {
  components: {
    BatchAction,
    BatchAction2,
    STable,
    Ellipsis
  },
  name: 'States',
  data () {
    return {
      headers: {
        'Access-Token': storage.get(ACCESS_TOKEN)
      },
      // 多选框样式
      checkStyle: {
        display: 'block',
        height: '40px',
        lineHeight: '40px'
      },
      // 表单输入控件样式
      tklabelCol: { span: 5 },
      tkwrapperCol: { span: 12, offset: 1 },
      labelCol: { span: 8 },
      wrapperCol: { span: 14, offset: 1 },
      // 确定按钮加载事件
      loading: false,
      advanced: true,
      // 控制编辑弹窗显示/隐藏
      trademarkVisible: false,
      // 控制回执弹窗显示/隐藏
      receiptVisible: false,
      receiptList: {},
      receiptState: {},
      receiptForm: {},
      changeForm: {
        sb_name: '',
        sb_category: '',
        sb_reg_no: '',
        state_id: '',
        official_order_no: ''
      },
      businessOpts: {},
      changeStatusOpts: {},
      changeStatusForm: {},
      radioStyle: {
        display: 'block',
        height: '40px',
        lineHeight: '40px'
      },
      // 控制状态弹窗显示/隐藏
      stateVisible: false,
      queryParam: {},
      searchSource: [],
      uploadUrl: apis.Upload,
      tradeColumns: trademarkColumns.tradeinformation,
      receiptData: parameters => {
        return getCollectList(Object.assign(parameters, this.queryParam)).then(res => {
          this.businessOpts = res.result.businesses
          this.adviserOpts = res.result.adviserOpts
          return res.result
        })
      },
      settingsVisible: false,
      settingsVisible2: false,
      historyVisible: false,
      adviserOpts: {},
      historyData: parameters => {
        return new Promise(resolve => {
          resolve({
            data: [
              {
                xu: '1',
                file_type: '驳回',
                created_at: '2021-03-09 10:49:22',
                uploader: '刘曼曼'
              },
              {
                xu: '2',
                file_type: '回执',
                created_at: '2021-03-09 10:49:22',
                uploader: '曹晨慧'
              },
              {
                xu: '3',
                file_type: '下证',
                created_at: '2021-03-09 10:49:22',
                uploader: '陈雪'
              }
            ]
          })
        })
      },
      importVisible: false,
      historyColumns: trademarkColumns.history,
      statusOpts: {},
      importForm: {},
      importRules: {
        business_id: [{ required: true, message: '请选择业务分类', trigger: 'blur' }],
        state_id: [{ required: true, message: '请选官方状态', trigger: 'blur' }],
        filename: [{ required: true, message: '请上传受通压缩包', trigger: 'blur' }]
      },
      stateOpts: {},
      recpVisible: false,
      searchInput: null,
      searchText: '',
      searchedColumn: ''
    }
  },
  methods: {
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    reset () {
      this.queryParam = {}
      this.$refs.table.refresh(true)
    },
    onChangeTime (date, dateString) {
      this.queryParam['filter[open_time_start]'] = dateString[0]
      this.queryParam['filter[open_time_end]'] = dateString[1]
    },
    // 编辑弹窗确定按钮事件
    trademarkModal (id) {
      const app = this
      app.changeForm = {}
      getTrademarkEdit(id).then(res => {
        if (res.status === 0) {
          app.changeForm = res.result
          app.changeForm['cb_id'] = id
          getTrademarkStatusEdit(id).then(res => {
            if (res.status === 0) {
              app.changeStatusForm['cb_id'] = id
              app.changeStatusOpts = res.result
              app.trademarkVisible = true
            }
          })
        }
      })
      this.receiptModal(id)
    },
    submitTrademark () {
      const app = this
      const rData = {}
      const eData = {}
      app.loading = true
      rData['contractBusiness[sb_name]'] = app.changeForm.sb_name
      rData['contractBusiness[sb_category]'] = app.changeForm.sb_category
      rData['contractBusiness[sb_reg_no]'] = app.changeForm.sb_reg_no
      rData['contractBusiness[official_order_no]'] = app.changeForm.official_order_no
      postTrademarkEdit(app.changeForm['cb_id'], rData).then(res => {
        if (res.status === 0) {
          if (app.changeForm.state_id !== '' && app.changeForm.file !== '') {
            eData['contract_business_state[file]'] = app.changeForm.file
            eData['contract_business_state[filename]'] = app.changeForm.filename
            eData['contract_business_state[state_id]'] = app.changeForm.state_id
            postReceiptState(app.changeForm['cb_id'], eData).then(res => {
              if (res.status === 0) {
                app.trademarkVisible = false
                app.$refs.table.refresh()
              }
            })
          }
        } else {
          app.$warning({
            title: res.msg
          })
        }
      }).finally(() => {
        this.loading = false
      })
    },
    submitResetStatus () {
      const app = this
      const data = {}
      data['contractBusiness[status2]'] = app.changeStatusForm.status2
      postTrademarkStatusEdit(app.changeStatusForm['cb_id'], data).then(res => {
        if (res.status === 0) {
          this.$refs.table.refresh()
          app.changeStatusForm = {}
          app.stateVisible = false
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
      this.stateVisible = false
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    toDetail (id) {
      this.$router.push({ name: 'TrademarkEdit', params: { id } })
    },
    onSetCancel (visible) {
      this.settingsVisible = visible
    },
    onSetCancel2 (visible) {
      this.settingsVisible2 = visible
    },
    copy () {
      const clipboard = new Clipboard('.copy')
      clipboard.on('success', e => {
        this.$message.success('复制成功')
      })
      clipboard.on('error', e => {
        this.$message.error('复制失败')
      })
    },
    receiptModal (id) {
      const app = this
      getReceiptState(id).then(res => {
        if (res.status === 0) {
          app.receiptList = res.result.state_opts
          app.getHistoryData(app.changeForm['cb_id'])
        } else {
          app.warning({
            title: res.msg
          })
        }
      })
    },
    getHistoryData (id) {
      getReceiptList(id).then(res => {
        if (res.status === 0) {
          this.receiptState = res.result.data
        }
      })
    },
    handleSearch (selectedKeys, confirm, dataIndex) {
      confirm()
      this.searchText = selectedKeys[0]
      this.searchedColumn = dataIndex
    },
    handleReset (clearFilters) {
      clearFilters()
      this.searchText = ''
    },
    // 状态单选按钮
    onChangeStatus (e) {
      this.receiptForm.state_id = e.target.value
    },
    onChangeRadio (e) {
      this.changeStatusForm.status2 = e.target.value
    },
    // 文件上传
    onChange (info) {
      if (info.file.status === 'uploading') {
        return false
      }
      if (info.file.status === 'done') {
        this.changeForm['filename'] = info.file.name
        this.changeForm['file'] = info.file.response.result.url
        this.getHistoryData(this.changeForm['cb_id'])
      }
    },
    download (value, filename) {
      // window.open(apis.Download + '?value=' + value + '&filename=' + filename)
      window.open(value)
    },
    submitReceipt (file, filename, id) {
      const app = this
      const data = {}
      data['contract_business_state[file]'] = file
      data['contract_business_state[filename]'] = filename
      data['contract_business_state[state_id]'] = id
      postReceiptState(app.changeForm['cb_id'], data).then(res => {
        if (res.status === 0) {
          app.receiptForm.file = 'xxx'
          app.receiptForm.filename = '无'
          app.getHistoryData(app.receiptForm['cb_id'])
        } else {
          app.$warning({
            title: res.msg
          })
        }
      })
    },
    cancelReceipt () {
      this.$refs.table.refresh()
    },
    delState (id) {
      const app = this
      app.$confirm({
        title: '是否删除官方状态',
        onOk: () => {
          getReceiptDelete(id).then(res => {
            if (res.status === 0) {
              app.getHistoryData(app.receiptForm['cb_id'])
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        }
      })
    },
    onHistory () {
      this.historyVisible = true
    },
    resetStatus (id) {
      const app = this
      getTrademarkStatusEdit(id).then(res => {
        if (res.status === 0) {
          app.changeStatusForm['cb_id'] = id
          app.changeStatusOpts = res.result
          app.stateVisible = true
        }
      })
    },
    onSetting () {
      this.settingsVisible = true
    },
    onSetting2 () {
      this.settingsVisible2 = true
    },
    onImport () {
      this.importForm = {}
      getImport().then(res => {
        if (res.status === 0) {
          this.importVisible = true
        } else {
          this.$warning({
            title: res.msg
          })
        }
      })
    },
    onSelect (key) {
      getImportByState(key).then(res => {
        if (res.status === 0) {
          this.importForm['business_id'] = key
          this.stateOpts = res.result.state_opts
        } else {
          this.$warning({
            title: res.msg
          })
        }
      })
    },
    onSelect2 (key) {
      this.importForm['state_id'] = key
      // this.importForm['state_name'] = this.stateOpts[key]
    },
    changeUpload (info) {
      if (info.file.status === 'uploading') {
        return false
      }
      if (info.file.status === 'done') {
        this.importForm['filename'] = info.file.name
        this.importForm['value'] = info.file.response.result.url
      }
    },
    onSubmit () {
      const app = this
      const data = {}
      app.$refs.importForm.validate(valid => {
        if (valid) {
          data['file[filename]'] = app.importForm['filename']
          data['file[value]'] = app.importForm['value']
          data['arr[business_id]'] = app.importForm['business_id']
          // data['arr[state_name]'] = app.importForm['state_name']
          data['arr[state_id]'] = app.importForm['state_id']
          postImport(app.importForm['business_id'], data).then(res => {
            if (res.status === 0) {
              app.importVisible = false
              app.$refs.table.refresh()
            } else {
              app.$warning({
                title: res.msg
              })
            }
          })
        } else {
          return false
        }
      })
    },
    onRec () {
      this.recpVisible = true
    }
  }
}
</script>

<style scoped>

</style>
